import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';

import 'package:rss_readneed/punch_card/punchCardModel.dart';
import 'package:rss_readneed/public.dart';

import 'package:rss_readneed/sn_support/SNAccount.dart';

Effect<simple_show_snState> buildEffect() {
  return combineEffects(<Object, Effect<simple_show_snState>>{
    Lifecycle.initState:_initAction,
    Lifecycle.deactivate:_deactivate,
    Lifecycle.dispose:_dispose,
    simple_show_snAction.changeCheckAction:_changeCheckAction,
    simple_show_snAction.changeFirstPage:_changeFirstPage,
  });
}

void _initAction(Action action, Context<simple_show_snState> ctx) {

  monthTotalInfo(ctx);

  PunchCardSettingModel.noti.stream.listen((_){

    monthTotalInfo(ctx);
  });

  ctx.state.scrollController.addListener((){
    print(ctx.state.scrollController.offset);

    if (ctx.state.scrollController.offset <= 0){

      ctx.state.alpha = 1;
    } else if (ctx.state.scrollController.offset < 50 && ctx.state.scrollController.offset > 0) {

      ctx.state.alpha = (50 - ctx.state.scrollController.offset).abs()/50;
    } else {

      ctx.state.alpha = 0;
    }
    //刷新页面展示
    ctx.dispatch(simple_show_snActionCreator.onAction());
  });
}

//push:deactivate->build 页面会进入不可用状态，并重新build(但不会绘制),A页面不会卸载。
//pop:deactivate->build 页面进入运行状态
void _deactivate(Action action, Context<simple_show_snState> ctx) async {

  String pageShortString = AppNavigator.instance.locationPageShortString;
  if (pageShortString.contains("/")) {

    //更新统计数据
    monthTotalInfo(ctx);
  }
}

//刷新统计数据 - 平均下班时间
void monthTotalInfo(Context<simple_show_snState> ctx) async {

  PunchCardSettingModel monthModel = await PunchCardSettingModel().getModel(DateTime.now().toString().substring(0,7));

  ctx.state.monthModel = monthModel;

  List<PunchCardModel> monthList = await PunchCardSettingModel().monthDatas(monthModel);

  if (monthList == null) return ;

  List<PunchCardModel> datasStore = [];//倒序处理，展示
  for (PunchCardModel model1 in monthList) {

    datasStore.insert(0, model1);
  }
  ctx.state.datas = datasStore;//数据存储下来
  int total = 0;
  int dayCount = 0;
  for (PunchCardModel dayModel in monthList) {

    if (dayModel.inCount) {

      Duration duration = DateTime.parse(dayModel.finishTime).difference(DateTime.parse(dayModel.dateTime + monthModel.finishTime.substring(10)));

      total += duration.inMinutes;
      dayCount += 1;
    }
  }
  if (total <= 0 || dayCount <= 0) {
    ctx.state.totalShowTime = "00:00";
    ctx.state.alreadyfinishTime = monthModel.finishTime;//这个时间点的日期不对,因为要用时间获取颜色,所以存储整体，展示截断
  } else {//设定的下班时间 + 总时间/统计天数
    ctx.state.totalShowTime = (total/60).floor().toString() + ":" + (total%60).toString();
    ctx.state.alreadyfinishTime = DateTime.parse(monthModel.finishTime).add(Duration(minutes:(total/dayCount).floor())).toString();//上方注释
  }
  //月度计划计算
  ctx.state.monthPlanTime = "20:30";//暂定20:30,不予配置
  if (ctx.state.monthPlanTime != null) {
    //已存在的最后一条数据
    PunchCardModel lastExitModel = monthList.last;
    //本月最后一天
    //取下个月的第一天使用while语句
    DateTime nextMonthFirstDay = DateTime.parse(monthModel.monthTime + "-32");

    //取计划规划的第一天 - 已存在数据的第二天
    DateTime planFirstDay = DateTime.parse(lastExitModel.dateTime).add(Duration(days: 1));
    int leftDayCount = 0;
    while (planFirstDay.isBefore(nextMonthFirstDay)) {

      PunchCardModel model = PunchCardModel().initModelWith(planFirstDay);
      if (model.inCount){

        dayCount += 1;
        leftDayCount += 1;
      }
      planFirstDay = planFirstDay.add(Duration(days: 1));
    }

    if (leftDayCount > 0) {

      //拿到每天计划时长
      int planMinutes = DateTime.parse(monthModel.monthTime + "-01" + " " + ctx.state.monthPlanTime + ":00").difference(DateTime.parse(monthModel.monthTime + "-01" + monthModel.finishTime.substring(10))).inMinutes;
      //用每天的计划时长乘以总天数
      int allMinutes = planMinutes * dayCount;

      int leftMinutes = allMinutes - total;
      //剩余天数应该理论下班时间
      String leftDayPlanFinishTime = DateTime.parse(monthModel.finishTime).add(Duration(minutes:(leftMinutes/leftDayCount).ceil())).toString().substring(11,16);

      ctx.state.leftDayPlanFinishTime = leftDayPlanFinishTime;
    }
  }

  //刷新页面展示
  ctx.dispatch(simple_show_snActionCreator.onAction());
}

void _dispose(Action action, Context<simple_show_snState> ctx) {

  ctx.state.scrollController.dispose();
}

void _changeCheckAction(Action action, Context<simple_show_snState> ctx) {

  PunchCardModel model = action.payload;

  PunchCardModel newModel = PunchCardModel(
    yearTime: model.yearTime,
    monthTime: model.monthTime,
    dateTime: model.dateTime,
    todayThings: model.todayThings,
    finishTime: model.finishTime,
    workingThings: model.workingThings,
    tomorrowThings: model.tomorrowThings,
    inCount:!model.inCount,
  );
  //变更存储数据
  PunchCardModel().save(newModel, true);
  //变更显示数据
  int index = ctx.state.datas.indexOf(model);

  ctx.state.datas.removeAt(index);
  ctx.state.datas.insert(index, newModel);

  ctx.dispatch(simple_show_snActionCreator.onAction());

}

void _changeFirstPage(Action action, Context<simple_show_snState> ctx) {

  SNAccount().save(SNAccount.instance.account, SNAccount.instance.password, false);
}
